package cn.tac.test.mybatis.typehandler;

import cn.tac.test.mybatis.constant.TestEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author : tac
 * @since : 04/09/2017
 */
@MappedJdbcTypes(JdbcType.VARCHAR)  //这个handler会覆盖掉原有的VARCHAR对应的Integer类型的handler
public class MyVarchar2TestEnumTypeHandler extends BaseTypeHandler<TestEnum> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, TestEnum parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, Integer.toString(parameter.val));
    }

    @Override
    public TestEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return wrapStr(rs.getString(columnName));
    }

    @Override
    public TestEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return wrapStr(rs.getString(columnIndex));
    }

    @Override
    public TestEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return wrapStr(cs.getString(columnIndex));
    }

    private TestEnum wrapStr(String str) throws SQLException {
        return TestEnum.mapVal(Integer.parseInt(str));
    }
}
